/* 
 * Copyright (c) 2021, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.boot.support.spring.converter;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

/**
 * @author xiongcong
 * @date 2021-06-08
 */
@Component
public class LocalDateConverter implements Converter<String, LocalDate> {
    
    private static final List<String> formarts = new ArrayList<>(2);
    
    static {
        formarts.add("yyyy-MM");
        formarts.add("yyyy-MM-dd");
    }

    @Override
    public LocalDate convert(String source) {
        String value = source.trim();
        if ("".equals(value)) {
            return null;
        }
        if (source.matches("^\\d{4}-\\d{1,2}$")) {
            return parseDate(source, formarts.get(0));
        } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
            return parseDate(source, formarts.get(1));
        } else {
            throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
        }
    }

    private LocalDate parseDate(String dateStr, String format) {
        try {
            DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(format);
            return LocalDate.parse(dateStr, dateFormat);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
